package rensoft.gwt.client.lang;

import com.google.gwt.core.client.Scheduler;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;

import cs.java.json.JSON;
import cs.java.lang.Lang.Work;
import cs.java.lang.LangCore;
import cs.java.lang.LangCoreImplBase;
import cs.java.lang.Run;
import rensoft.gwt.client.platform.json.JSONImpl;

public class GwtLangCore extends LangCoreImplBase implements LangCore {

	@Override public void alert(Object... messages) {
		Window.alert(getAlertString(messages));
	}

	public void debug(Object... values) {
		System.out.println(getDebugString(values));
	}

	public void doLater(int delay_miliseconds, final Runnable runnable) {
		if (delay_miliseconds == 0) doLater(runnable);
		else new Timer() {
			@Override public void run() {
				runnable.run();
			}
		}.schedule(delay_miliseconds);
	}

	public void doLater(final Runnable runnable) {
		Scheduler.get().scheduleDeferred(new Command() {
			public void execute() {
				runnable.run();
			}
		});
	}

	public void error(Object... values) {
		error(new Throwable(), values);
	}

	public void error(Throwable e, Object... values) {
		System.out.println(getErrorString(e, values));
	}

	public void info(Object... values) {
		System.out.println(getInfoString(values));
	}

	public JSON json() {
		return new JSONImpl();
	}

	public Work schedule(final int delay_miliseconds, final Run runnable) {
		final Timer timer = new Timer() {
			@Override public void run() {
				runnable.run();
			}
		};
		return new Work() {
			public void run() {
				runnable.run();
			}

			public void start() {
				timer.scheduleRepeating(delay_miliseconds);
			}

			public void stop() {
				timer.cancel();
			}
		};
	}

	public void trace(Object... values) {
		System.out.println(getTraceString(values));
	}

	@Override public String urlEncode(String argument) {
		return URL.encode(argument);
	}
}
